﻿using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace Magic.Redis;

/// <summary>
/// 基于 <see cref="CSRedis"/>实现的redis客户端；
/// </summary>
public sealed partial class CsRedisCoreClient : IRedisClient
{
	/// <summary>
	/// RedisClient.
	/// </summary>
	/// <param name="logger"></param>
	public CsRedisCoreClient(
		ILoggerFactory logger
		)
	{
		_logger = logger.CreateLogger<CsRedisCoreClient>();
	}
	/// <summary>
	/// 初始化redis客户端；
	/// </summary>
	/// <param name="connectionString"></param>
	public void Initialization(string connectionString)
	{
		RedisHelper.Initialization(new CSRedis.CSRedisClient(connectionString));
	}

	#region 私有成员
	private readonly ILogger _logger;
	private const string LOGGER_TAG = "Cytclinic.Infrastructure.Cache.CsRedisCoreClient";

	private static string Serialize(object data)
	{
		if ((data is string) || (data.GetType().IsValueType))
		{
			return data.ToString();
		}
		return JsonConvert.SerializeObject(data);

	}

	private static T Deserialize<T>(string json)
	{
		var t = typeof(T);
		if (t == typeof(string) || t == typeof(DateTime) || t.IsValueType)
		{
			return (T)Convert.ChangeType(json, t);
		}
		return JsonConvert.DeserializeObject<T>(json);
	}

	/// <summary>
	/// 记录异常类型的日志
	/// </summary>
	/// <param name="message"></param>
	/// <param name="ex"></param>
	private void Faild(string message, Exception ex)
	{
		_logger.LogError(message: $"{LOGGER_TAG}{message}\r\n{ex.Message}\r\n{ex.StackTrace}");
	}
	#endregion End 私有成员
}
